<template>
	<view class="">
		<loading ref="loading"></loading>
		<view class="bg_img" :style="{background: 'url('+detail.images[index]+')',backgroundSize: 'cover'}"></view>
		<view class="u-flex u-row-center u-col-center u-p-t-60 u-p-b-20" style="position: relative;">
			<image :src="detail.images[index]" @load="play" style="height: 70vw;width: 70vw;display: flex;border-radius: 24rpx;" mode="aspectFill"></image>
		</view>
		<view class="u-flex u-row-center">
			<view class="bottom">
				<view class="nav-box">
					<view class="nav-tab" @click="backClick">
						<u-icon name="/static/icon/back.png" :size="44"></u-icon>
						<text>返回</text>
					</view>
					<view class="nav-tab" @click="addView(detail._id,1)">
						<u-icon name="/static/icon/zan.png" :size="42"></u-icon>
						<text>点赞</text>
					</view>
					<view class="nav-tab" @click="winClick">
						<u-icon name="/static/icon/duihuan.png" :size="42"></u-icon>
						<text>下载</text>
					</view>
					<view class="nav-tab" @click="copyClick(detail.code)">
						<u-icon name="/static/icon/copy.png" :size="40"></u-icon>
						<text>口令</text>
					</view>
					<view class="nav-tab">
						<u-icon name="/static/icon/shares_b.png" :size="44"></u-icon>
						<text>分享</text>
						<button open-type="share" style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;opacity: 0;"></button>
					</view>
				</view>
			</view>
		</view>
		<view class="u-m-t-40">
			<ad v-if="vk.getVuex('$setting.client.banner_id')" :unit-id="vk.getVuex('$setting.client.banner_id')" type="banner" ad-theme="black"></ad>
		</view>
		<view class="u-p-t-30" v-if="coverList.length > 0">
			<view class="u-p-l-20 u-p-r-20 u-p-b-20">
				<u-section title="随机推荐" 
				:color="vk.getVuex('$app.config.color.main')"
				:sub-color="vk.getVuex('$app.config.color.sec')"
				:line-color="vk.getVuex('$app.config.color.sec')"
				:bold="false" 
				font-size="32" 
				:arrow="false" 
				sub-title="换一批" 
				@click="getList"></u-section>
			</view>
			<view class="u-flex u-row-left u-flex-wrap u-p-l-20 u-p-t-20">
				<block v-for="(item, index) in coverList" :key="index">
					<block v-for="(item_, index_) in item.images" :key="index_">
						<view class="tab" @click="lookDetail(item._id, index_)">
							<image :src="item_+(vk.getVuex('$setting.thumb.look_flag')===1?vk.getVuex('$setting.thumb.look_style'):'')" mode="aspectFill"></image>
						</view>
					</block>
				</block>
			</view>
		</view>
		<!-- <view v-if="tipsShow" style="position: absolute;top: 0;left: 0;width: 100vw;height: 100vh;z-index: 11;" @click="tipsClick">
			<image src="../../static/tips.png" style="width: 100%;height: 100%;display: flex;" mode="aspectFill"></image>
		</view> -->
		
		<models v-if="loginShow"
		title="为了更好的玩机体验，点击下方按钮授权登录吧~"
		:authorize="true"
		btnText="授权登录" 
		@mask="loginShow = false" 
		@close="loginShow = false"></models>
		
		<models v-if="model.show"
		:ad="model.ad" 
		:title="model.title" 
		:btnText="model.btn" 
		:download="model.download" 
		:closeText="model.close" 
		@mask="model.show = false" 
		@close="model.show = false" 
		@plain="plainClick" 
		@save="modelClick"></models>
	</view>
</template>

<script>
	let videoAd = null;
	var w = uni.getSystemInfoSync().windowWidth;
	var h = uni.getSystemInfoSync().windowHeight;
	export default {
		data() {
			return {
				loginShow: false,
				index: 0,
				detail: {},
				coverList: [],
				
				// 下载弹窗
				model: {
					type: '',
					title: '',
					btn: '',
					close: '',
					ad: false,
					download: false,
					show: false,
				},
				
				pageFlag: '',
				likeFlag: false,
				downFlag: false,
				adCount: 0,
				
				w: w,
				h: h,
			}
		},
		async onLoad({id,index,flag}) {
			var that = this
			that.index = index
			that.pageFlag = flag
			await that.getDetail(id)
			if(that.vk.getVuex('$user.userInfo._id')){
				that.getOrderNum()
			}
			that.addView(id)
			// #ifdef MP
			that.adLoad()
			// #endif
		},
		methods: {
			play(){
				var that = this
				that.$nextTick(() => {
					that.$refs.loading.closeLoading()
				})
			},
			async getDetail(id){
				var that = this
				let data = await that.vk.callFunction({
					url: 'client/wechat/list/pub/findOne',
					data:{
						dbName: 'bus-wx-cover',
						whereJson: {
							_id: id
						},
						foreignDB: [{
							dbName: "uni-id-users",
							localKey:"user_id",
							foreignKey: "_id",
							as: "user",
							limit: 1
						}]
					}
				});
				if(data.info.status != 1){
					uni.showToast({
						// #ifdef MP-TOUTIAO
						icon: 'fail',
						// #endif
						// #ifndef MP-TOUTIAO
						icon: 'error',
						// #endif
						mask: true,
						duration: 2000,
						title: '该作品暂未上线'
					})
					setTimeout(function(){
						uni.navigateBack()
					},1800)
					return
				}
				if(data.info){
					that.downFlag = false
					that.detail = data.info
					that.getList(1)
				}
			},
			async getOrderNum(){
				var that = this
				let data = await that.vk.callFunction({
					url: 'client/wechat/list/kh/count',
					data:{
						dbName: 'bus-wx-order',
						user_id: that.vk.getVuex('$user.userInfo._id'),
						origin: '_ad',
						day: true
					},
				});
				if(data.num > 0) that.adCount = data.num
			},
			async lookDetail(id,index){
				var that = this
				uni.showLoading({
					mask: true,
					title: '加载中...'
				})
				await that.getDetail(id)
				await that.addView(id)
				if(that.vk.getVuex('$user.userInfo._id')){
					that.getOrderNum()
				}
				that.index = index
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
				uni.hideLoading()
			},
			async getList(on){
				let that = this;
				let data = await that.vk.callFunction({
					url: 'client/wechat/list/pub/sample',
					data:{
						dbName: 'bus-wx-cover',
						size: 3,
						whereJson: {
							mode: 5,
							status: 1,
							id: that.detail._id
						}
					}
				});
				let list = []
				if(on === 1) list.push(that.detail)
				that.coverList = list.concat(data.rows)
			},
			homeClick(id){
				console.log(id)
				uni.navigateTo({
					url: '/pages/write/home?id='+id+'&mode=2'
				})
			},
			copyClick(e) {
				var that = this
				that.$u.toast('敬请期待~');
			},
			async addView(id,on){
				var that = this
				if(on === 1 && that.likeFlag){
					that.$u.toast('让小猫歇一会~');
					return
				}
				that.likeFlag = true
				let data = await that.vk.callFunction({
					url: 'client/wechat/list/pub/addView',
					data:{
						dbName: 'bus-wx-cover',
						id: id
					}
				});
				if(on === 1 && data.code === 0){
					that.$u.toast('热度+1');
				}
				setTimeout(function(){
					that.likeFlag = false
				},3000)
			},
			backClick(){
				uni.navigateBack()
			},
			async winClick(){
				var that = this
				if(!that.vk.getVuex('$user.userInfo._id')){
					that.loginShow = true
					return
				}
				if(that.downFlag || that.vk.getVuex('$user.userInfo._id')===that.detail.user_id){
					that.downFile()
					return
				}
				let model = await that.vk.myfn.downModel('look', that.adCount)
				if(model.show){
					that.model = model
				}else{
					// 处理订单
					let res = await that.upOrder('free')
					that.downFile()
				}
			},
			async modelClick(){
				var that = this
				if(that.model.type === 'vip'){
					let res = await that.upOrder('vip')
					that.downFile()
				}else if(that.model.type === 'down'){
					let res = await that.upOrder('score')
					that.downFile()
				}else if(that.model.type === 'ad' || that.model.type === 'video'){
					that.adClick()
				}
				that.model.show = false
			},
			plainClick(){
				var that = this
				that.model.show = false
				that.downFile(1)
			},
			async upOrder(origin){
				let that = this;
				uni.showLoading({
					mask: true,
					title: '保存中...'
				})
				let data = await that.vk.callFunction({
					url: 'client/wechat/list/kh/setOrder',
					data:{
						user_id: that.vk.getVuex('$user.userInfo._id'),
						detail_id: that.detail._id,
						type: 'look',
						origin,
						index: that.index
					}
				});
				uni.hideLoading()
				that.downFlag = true
				if(data.user) that.vk.setVuex('$user.userInfo.score', data.user.score)
				return data
			},
			adClick(){
				var that = this
				videoAd.show()
			},
			adLoad(){
				var that = this
				let adUnitId = that.vk.getVuex('$setting.client.videos_id')
				if(adUnitId){
					// 加载激励视频广告
					videoAd = uni.createRewardedVideoAd({
						adUnitId: adUnitId
					});
					//捕捉错误
					videoAd.onError(err => {
						// 进行适当的提示
						switch (err.errCode) {
							case 1004:
								videoAd.load()
								videoAd.show()
								break;
							default:
								that.$u.toast('广告拉取失败，请稍后再试！')
						}
					});
					// 监听关闭
					videoAd.onClose((status) => {
						if (status.isEnded) {
							// 正常播放结束，下发奖励
							that.adDown()
						} else {
							// 播放中途退出，进行提示
							that.$u.toast('中途退出，无法获得奖励！');
						}
					});
					videoAd.load();
				}
			},
			async adDown(){
				var that = this
				if(that.model.type === 'video'){
					uni.showLoading({
						mask: true,
						title: '加载中...'
					})
					// 请求后台增加积分
					let res = await that.vk.myfn.upScore(that.vk.getVuex('$user.userInfo._id'),'video','观看视频广告')
					uni.hideLoading()
					// 看完广告  增加积分
					that.model.type = 'colse'
					that.model.title = "<div style='padding-top: 10px;'>观看成功，恭喜你获得<span class='num' style='color: "+that.vk.getVuex('$app.config.color.sec')+"'>"+res.score+"</span>"+that.vk.getVuex('$setting.score.name')+"，当前有<span class='num' style='color: "+that.vk.getVuex('$app.config.color.sec')+"'>"+that.vk.getVuex('$user.userInfo.score')+"</span>"+that.vk.getVuex('$setting.score.name')+"，赶紧去下载吧~</div>"
					that.model.btn = '我知道了'
					that.model.close = ' '
					that.model.ad = false
					that.model.download = false
					that.model.show = true
				}else if(that.model.type === 'ad'){
					// 处理订单
					let res = await that.upOrder('ad')
					that.downFile()
				}
			},
			downFile(on){
				var that = this
				uni.showLoading({
					mask: true,
					title: '保存中...'
				})
				let url = that.detail.images[that.index]
				let extension = url.substring(url.lastIndexOf('.') + 1)
				let fileName = new Date().valueOf()
				if(on===1) url = url + '?x-oss-process=image/resize,m_lfit,w_200'
				uni.downloadFile({
					url: url,
					// #ifdef MP-WEIXIN
					filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.' + extension,
					// #endif
					success: (res) => {
						// #ifdef MP-WEIXIN
						var benUrl = res.filePath
						// #endif
						// #ifndef MP-WEIXIN
						var benUrl = res.tempFilePath
						// #endif
						//图片保存到本地相册
						uni.saveImageToPhotosAlbum({
							filePath: benUrl,
							//授权成功，保存图片
							success: function(data) {
								uni.hideLoading()
								that.model.type = 'share'
								that.model.title = '已成功保存到系统相册，别忘了分享给朋友也来下载哦！'
								that.model.btn = '分享给好友'
								that.model.close = '再想想看'
								that.model.ad = true
								that.model.download = false
								that.model.show = true
							},
							//授权失败
							fail: function(err) {
								uni.hideLoading()
								if (err.errMsg) {
									//重新授权弹框确认
									uni.showModal({
										title: '温馨提示',
										content: '打开相册权限后下载！',
										showCancel: false,
										success(res) {
											if (res.confirm) {
												uni.openSetting({
													success() {}
												});
											}
										}
									});
								}
							}
						});
					},
					fail: (error) => {
						console.log(error)
					}
				})
			},
			// 授权登录
			getUserInfo(){
				var that = this
				that.loginShow = false
				uni.showLoading({
					mask: true,
					title: '授权中...'
				})
				uni.getUserProfile({
				    desc: '更新您的个人信息',
				    success: async (res) => {
						uni.hideLoading()
						uni.login({
							success: async function({code}) {
								let data = await that.vk.myfn.userLogin(code,res.userInfo)
								if(data.code === 0){
									that.getOrderNum()
								}
							},
						});
				    },
				    fail(err){
						uni.hideLoading()
					    uni.showToast({
							icon: 'none',
							title: '授权失败',
							duration: 1500
					    })
				    }
				})
			},
		},
		onShareAppMessage(res) {
			return {
				title: '送你一张超级好看的表情包~',
				imageUrl: this.detail.images[this.index],
				path: 'pages/index/index?inviteId='+(this.vk.getVuex('$user.userInfo._id')?this.vk.getVuex('$user.userInfo._id'):'')+'&detailId='+this.detail._id+'&index='+this.index+'&type=look'
			}
		}
	}
</script>
<style lang="scss" scoped>
	.bg_img{
		width: 100%;
		height: calc(60vw + 80rpx + 52px + 40rpx + 50rpx);
		background-repeat: no-repeat;
		-webkit-filter: blur(15px);
		-moz-filter: blur(15px);
		-o-filter: blur(15px);
		-ms-filter: blur(15px);
		filter: blur(15px);
		position: absolute;
		left: 0;
		top: 0;
		opacity: 0.8;
	}
	.bottom {
		width: 92%;
		height: 52px;
		// box-shadow: 0 0px 8px rgba(0, 0, 0, 0.06);
		background: #282828;
		border-radius: 49px;
		// z-index: 10;
		opacity: 0.8;
	}
	.user{
		animation: tiaobig 4s ease-in-out alternate infinite;
		position: relative;
		background: rgba(31, 31, 31, 0.7);
		color: #FFF;
		height: 50rpx;
		padding: 0 30rpx 0 0;
		font-size: 14px;
		border-radius: 70rpx;
		.nick{
			position: relative;
			top: -1px;
			max-width: 180rpx;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}
	}
	@keyframes tiaobig {
		40% {
			transform: scale(1);
		}
		44% {
			transform: scale(1.06);
		}
		48% {
			transform: scale(0.96);
		}
		52% {
			transform: scale(1.04);
		}
		56% {
			transform: scale(0.98);
		}
		60% {
			transform: scale(1);
		}
	}

	.nav-tab {
		position: relative;
		width: 100%;
		height: 52px;
		font-size: 12px;
		color: #D8D8D8;
		font-weight: 400;

		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	.nav-box {
		/* position: absolute; */
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		width: 100%;
		box-sizing: border-box;
	}

	.u-indicator-item-number {
		padding: 6rpx 16rpx;
		line-height: 1;
		background-color: rgba(0, 0, 0, 0.3);
		border-radius: 100rpx;
		font-size: 26rpx;
		color: rgba(255, 255, 255, 0.8);
	}
	
	.tab{
		position: relative;
		margin-right: 16rpx;
		margin-bottom: 16rpx;
		border-radius: 12rpx;
		image{
			border-radius: 12rpx;
			width: 226rpx;
			height: 226rpx;
		}
		.array{
			position: absolute;
			top: 18rpx;
			right: 0rpx;
			color: #F8DE52;
			background-color: rgba(0, 0, 0, 0.4);
			padding: 0rpx 12rpx 0 16rpx;
			border-radius: 20rpx 0 0 20rpx;
			font-size: 12px;
		}
	}
	.hover-class{
		transform:scale(0.95);
		transition: all 0.2s;
	}
	
	/deep/ .num{
		font-size: 16px;
		font-weight: 700;
		padding: 0 8rpx;
	}
</style>